/*
 * Copyright 2005-2013 uphsh.com. All rights reserved.
 * Support: http://www.uphsh.com
 * Version: 1.0
 */

// 添加Cookie
var setting = {
	priceScale: "2",
	priceRoundType: "roundHalfUp",
	currencySign: "￥",
	currencyUnit: "元"
};

function addCookie(name, value, options) {
	if (arguments.length > 1 && name != null) {
		if (options == null) {
			options = {};
		}
		if (value == null) {
			options.expires = -1;
		}
		if (typeof options.expires == "number") {
			var time = options.expires;
			var expires = options.expires = new Date();
			expires.setTime(expires.getTime() + time * 1000);
		}
		document.cookie = encodeURIComponent(String(name)) + "=" + encodeURIComponent(String(value)) + (options.expires ? "; expires=" + options.expires.toUTCString() : "") + (options.path ? "; path=" + options.path : "") + (options.domain ? "; domain=" + options.domain : ""), (options.secure ? "; secure" : "");
	}
}

// 获取Cookie
function getCookie(name) {
	if (name != null) {
		var value = new RegExp("(?:^|; )" + encodeURIComponent(String(name)) + "=([^;]*)").exec(document.cookie);
		return value ? decodeURIComponent(value[1]) : null;
	}
}

// 移除Cookie
function removeCookie(name, options) {
	addCookie(name, null, options);
}

// 货币格式化
function currency(value, showSign, showUnit) {
	if (value != null) {
		var price;
		if (setting.priceRoundType == "roundHalfUp") {
			price = (Math.round(value * Math.pow(10, setting.priceScale)) / Math.pow(10, setting.priceScale)).toFixed(setting.priceScale);
		} else if (setting.priceRoundType == "roundUp") {
			price = (Math.ceil(value * Math.pow(10, setting.priceScale)) / Math.pow(10, setting.priceScale)).toFixed(setting.priceScale);
		} else {
			price = (Math.floor(value * Math.pow(10, setting.priceScale)) / Math.pow(10, setting.priceScale)).toFixed(setting.priceScale);
		}
		if (showSign) {
			price = setting.currencySign + price;
		}
		if (showUnit) {
			price += setting.currencyUnit;
		}
		return price;
	}
}

function checkIdcard(idcard) {
	var Errors = new Array("true", "身份证号码位数不对!", "身份证号码出生日期超出范围或含有非法字符!", "身份证号码校验错误!", "身份证地区非法!");
	var area = {11 : "北京",12 : "天津",13 : "河北",14 : "山西",15 : "内蒙古",21 : "辽宁",22 : "吉林",23 : "黑龙江",31 : "上海",32 : "江苏",
		33 : "浙江",34 : "安徽",35 : "福建",36 : "江西",37 : "山东",41 : "河南",42 : "湖北",43 : "湖南",44 : "广东",45 : "广西",46 : "海南",
		50 : "重庆",51 : "四川",52 : "贵州",53 : "云南",54 : "西藏",61 : "陕西",62 : "甘肃",63 : "青海",64 : "宁夏",65 : "新疆",71 : "台湾",
		81 : "香港",82 : "澳门",91 : "国外"
	};
	var idcard, Y, JYM;
	var S, M;
	var idcard_array = new Array();
	idcard_array = idcard.split("");
	//地区检验
	if(area[parseInt(idcard.substr(0, 2))] == null){
		return Errors[4];
	}
	//身份号码位数及格式检验
	switch(idcard.length) {
		case 15:
			if((parseInt(idcard.substr(6, 2)) + 1900) % 4 == 0 || ((parseInt(idcard.substr(6, 2)) + 1900) % 100 == 0 && (parseInt(idcard.substr(6, 2)) + 1900) % 4 == 0 )) {
				ereg = /^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}$/;
				//测试出生日期的合法性
			} else {
				ereg = /^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}$/;
				//测试出生日期的合法性
			}
			if(ereg.test(idcard)){
				return Errors[0];
			}else{
				return Errors[2];
			}
			break;
		case 18:
			//18位身份号码检测
			//出生日期的合法性检查
			//闰年月日:((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))
			//平年月日:((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))
			if(parseInt(idcard.substr(6, 4)) % 4 == 0 || (parseInt(idcard.substr(6, 4)) % 100 == 0 && parseInt(idcard.substr(6, 4)) % 4 == 0 )) {
				ereg = /^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}[0-9Xx]$/;
				//闰年出生日期的合法性正则表达式
			} else {
				ereg = /^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}[0-9Xx]$/;
				//平年出生日期的合法性正则表达式
			}
			if(ereg.test(idcard)) {//测试出生日期的合法性
				//计算校验位
				S = (parseInt(idcard_array[0]) + parseInt(idcard_array[10])) * 7 + (parseInt(idcard_array[1]) + parseInt(idcard_array[11])) * 9 + (parseInt(idcard_array[2]) + parseInt(idcard_array[12])) * 10 + (parseInt(idcard_array[3]) + parseInt(idcard_array[13])) * 5 + (parseInt(idcard_array[4]) + parseInt(idcard_array[14])) * 8 + (parseInt(idcard_array[5]) + parseInt(idcard_array[15])) * 4 + (parseInt(idcard_array[6]) + parseInt(idcard_array[16])) * 2 + parseInt(idcard_array[7]) * 1 + parseInt(idcard_array[8]) * 6 + parseInt(idcard_array[9]) * 3;
				Y = S % 11;
				M = "F";
				JYM = "10X98765432";
				M = JYM.substr(Y, 1);
				//判断校验位
				if(M == idcard_array[17]){
					return Errors[0];
				}else{//检测ID的校验位
					return Errors[3];
				}
			} else{
				return Errors[2];
			}
			break;
		default:
			return Errors[1];
			break;
	}
}


//货币格式化
function isBlank(value) {
	if (value === '' || typeof (value) == 'undefined'||value==='null'||value==null) {
		return true;
	}
	return false;
}


(function($) {
	var zIndex = 100;
	$.fn.selectBox = function(options) {
		var winheigth=$(window).height();
		var $boxOverlay=null;
		var $this=$(this);
		var $boxClose;
		var $boxTittle;
		var $boxContent;
		var $select_ul;
		var $selectInput=$("<input type='text' class='select_input'></input>");
		$selectInput.attr("readonly","readonly");
		if($this.data("placeholder")){
			$selectInput.attr("placeholder",$this.data("placeholder"));
		}
		$this.before($selectInput);
		
		$boxOverlay = $('<div class="boxOverlay"><\/div>').appendTo("body");
		$selectBox = $('<div class="selectBox"><\/div>').appendTo($boxOverlay);
		$boxTittle=$('<div class="boxTittle"><\/div>').appendTo($selectBox);
		if($this.data("tittle")){
			$boxTittle.html($this.data("tittle"));
		}
		$boxClose=$('<div class="boxClose"><b></b><\/div>').appendTo($selectBox);
		$boxContent=$('<div class="boxContent"><\/div>').appendTo($selectBox);
		$boxContent.height(winheigth-127);
		$select_ul = $('<ul></ul>').appendTo($boxContent);
		
		var $options=$this.find('option');
	    for(var i=0;i<$options.length;i++){
	    	if($options.eq(i).val()==''){
	    		continue;
	    	}
	    	if($options.eq(i).attr("selected")){
		    	$selectInput.val($options.eq(i).text());
		    }
	    }
	    
		$this.change(function(e){
   	   		$selectInput.val($this.find("option:selected").text());
 	   	});
		
		$selectInput.on('click',function (){
			var $options=$this.find('option');
			$select_ul.empty();
		    for(var i=0;i<$options.length;i++){
		    	if($options.eq(i).val()==''){
		    		continue;
		    	}
			    var $select_li=$('<li></li>').appendTo($select_ul);//li相当于option
			    if($options.eq(i).attr("selected")){
			    	$select_li.addClass("checked");
			    }
			    $select_li.text($options.eq(i).text()).css('cursor','pointer');
			    $select_li.data('option_value',$options.eq(i).val());
		        $select_li.on('click',function (){
		        	$(this).siblings().removeClass("checked");
		        	$(this).addClass("checked");
		        	$this.val($(this).data('option_value'));
		        	$this.change();
		        	$boxOverlay.hide();
		        }) ;
		    }
			$boxOverlay.show();
		});
		
		$boxClose.click(function() {
			$boxOverlay.hide();
			return false;
		});
	};
	$.fn.moneyInput = function(options) {
		this.each(function() {
			var reg=new RegExp(",","g");
			var s = this.value.replace(/\s/g,'').replace(reg,''); 
			if(s){
				s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(2) + "";//更改这里n数也可确定要保留的小数位  
				var l = s.split(".")[0].split("").reverse(),  
				r = s.split(".")[1];  
				t = "";  
				for(i = 0; i < l.length; i++ )  
				{  
					t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");  
				}  
				$(this).val(t.split("").reverse().join("") + "." + r.substring(0,2));
			}
			
			$(this).bind("cut copy paste", function(e) {  
                e.preventDefault();  
            });  
			
			$(this).bind('blur',function(e){
				var reg=new RegExp(",","g");
				var s = this.value.replace(/\s/g,'').replace(reg,''); 
				if(s){
					s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(2) + "";//更改这里n数也可确定要保留的小数位  
					var l = s.split(".")[0].split("").reverse(),  
					r = s.split(".")[1];  
					t = "";  
					for(i = 0; i < l.length; i++ )  
					{  
						t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");  
					}  
					$(this).val(t.split("").reverse().join("") + "." + r.substring(0,2));
				}
			});
		});

		return this;
	};
	
	// 消息框
	var $message;
	var messageTimer;
	$.message = function() {
		var message = {};
		if ($.isPlainObject(arguments[0])) {
			message = arguments[0];
		} else if (typeof arguments[0] === "string" && typeof arguments[1] === "string") {
			message.type = arguments[0];
			message.content = arguments[1];
		}else if (typeof arguments[0] === "string" && !arguments[1] ) {
			message.type = "tips";
			message.content = arguments[0];
		}  else {
			return false;
		}
		if (message.type == null || !message.content ) {
			return false;
		}
		
//		if ($message == null) {
//			$message = $('<div class="hshMessage"><div class="messageContent message' + message.type + 'Icon"><\/div><\/div>');
//			if (!window.XMLHttpRequest) {
//				$message.append('<iframe class="messageIframe"><\/iframe>');
//			}
//			$message.appendTo("body");
//		}
		
//		$message.children("div").removeClass("messagewarnIcon messageerrorIcon messagesuccessIcon").addClass("message" + message.type + "Icon").html(message.content);
//		$message.css({"margin-left": - parseInt($message.outerWidth() / 2), "z-index": zIndex ++}).show();
		
		if ($message == null) {
			$message = $('<div class="hshMessage"><\/div>').appendTo("body");
		}
		
		$message.html(message.content);
		$message.css({"margin-left": - parseInt($message.outerWidth() / 2),"margin-top": - parseInt($message.outerHeight() / 2),"top": parseInt($(window).height() / 2), "z-index": zIndex ++}).show();
	
		
		clearTimeout(messageTimer);
		messageTimer = setTimeout(function() {
			$message.hide();
		}, 3000);
		return $message;
	};

	// 对话框
	$.dialog = function(options) {
		var settings = {
			width: 320,
			height: "auto",
			modal: true,
			ok: "OK",
			cancel: "Cancel",
			onShow: null,
			onClose: null,
			onOk: null,
			onCancel: null
		};
		$.extend(settings, options);
		
		if (settings.content == null) {
			return false;
		}
		
		var $dialog = $('<div class="dialog" id="dialog"><\/div>');
		var $dialogTitle;
		//var $dialogClose = $('<div class="dialogClose"><\/div>').appendTo($dialog);
		var $dialogContent;
		var $dialogBottom;
		var $dialogOk;
		var $dialogCancel;
		var $dialogOverlay;
		if (settings.title != null) {
			$dialogTitle = $('<div class="dialogTitle"><\/div>').appendTo($dialog);
		}
		if (settings.type != null) {
			$dialogContent = $('<div class="dialogContent dialog' + settings.type + 'Icon"><\/div>').appendTo($dialog);
		} else {
			$dialogContent = $('<div class="dialogContent"><\/div>').appendTo($dialog);
		}
		if (settings.ok != null || settings.cancel != null) {
			$dialogBottom = $('<div class="dialogBottom"><\/div>').appendTo($dialog);
		}
		if (settings.ok != null) {
			$dialogOk = $('<input type="button" class="button" value="' + settings.ok + '" \/>').appendTo($dialogBottom);
		}
		if (settings.cancel != null) {
			$dialogCancel = $('<input type="button" class="button" value="' + settings.cancel + '" \/>').appendTo($dialogBottom);
		}
		if (!window.XMLHttpRequest) {
			$dialog.append('<iframe class="dialogIframe"><\/iframe>');
		}
		$dialog.appendTo("body");
		if (settings.modal) {
			$dialogOverlay = $('<div class="dialogOverlay" id="dialogOverlay"><\/div>').insertAfter($dialog);
		}
		
		var dialogX;
		var dialogY;
		if (settings.title != null) {
			$dialogTitle.text(settings.title);
		}
		$dialogContent.append($('<img alt="123" src="images/warn.png" width="60%">'));
		$dialogContent.append($('<br>'));
		$dialogContent.append(settings.content);
		$dialog.css({"width": settings.width, "height": settings.height, "margin-left": - parseInt(settings.width / 2), "z-index": zIndex ++});
		dialogShow();
		
		if ($dialogTitle != null) {
			$dialogTitle.mousedown(function(event) {
				$dialog.css({"z-index": zIndex ++});
				var offset = $(this).offset();
				if (!window.XMLHttpRequest) {
					dialogX = event.clientX - offset.left;
					dialogY = event.clientY - offset.top;
				} else {
					dialogX = event.pageX - offset.left;
					dialogY = event.pageY - offset.top;
				}
				$("body").bind("mousemove", function(event) {
					$dialog.css({"top": event.clientY - dialogY, "left": event.clientX - dialogX, "margin": 0});
				});
				return false;
			}).mouseup(function() {
				$("body").unbind("mousemove");
				return false;
			});
		}
		
//		if ($dialogClose != null) {
//			$dialogClose.click(function() {
//				dialogClose();
//				return false;
//			});
//		}
		
		if ($dialogOk != null) {
			$dialogOk.click(function() {
				if (settings.onOk && typeof settings.onOk == "function") {
					if (settings.onOk($dialog) != false) {
						dialogClose();
					}
				} else {
					dialogClose();
				}
				return false;
			});
		}
		
		if ($dialogCancel != null) {
			$dialogCancel.click(function() {
				if (settings.onCancel && typeof settings.onCancel == "function") {
					if (settings.onCancel($dialog) != false) {
						dialogClose();
					}
				} else {
					dialogClose();
				}
				return false;
			});
		}
		
		function dialogShow() {
			if (settings.onShow && typeof settings.onShow == "function") {
				if (settings.onShow($dialog) != false) {
					$dialog.show();
					$dialogOverlay.show();
				}
			} else {
				$dialog.show();
				$dialogOverlay.show();
			}
		}
		function dialogClose() {
			if (settings.onClose && typeof settings.onClose == "function") {
				if (settings.onClose($dialog) != false) {
					$dialogOverlay.remove();
					$dialog.remove();
				}
			} else {
				$dialogOverlay.remove();
				$dialog.remove();
			}
		}
		return $dialog;
	};
	
	// 对话框
	$.dialogClose = function(options) {
		$("#dialog").remove();
		$("#dialogOverlay").remove();
	};
	
	initInput = function() {
		var keys = new Array(8, 9, 35, 36, 37, 38, 39, 40, 46);
		var scale = 2;
		$("input").each(function (){
			$this=$(this);
			if($(this).data("maxlength")){
				var maxlength=$(this).data("maxlength");
				$this.on("keydown",function(e) {  
			        e = window.event || e;  
			        var code = e.which || e.keyCode;     
			        var idx = Array.indexOf(keys, code);  
			        if (idx != -1) {  
			            return true;  
			        }  
			        var value = this.value.replace(/\s+/g,"");
			        if($(this).data("maxlength")&&value.length>=$(this).data("maxlength")){
			        	return false;
			        }
			    });
				$this.on("keyup",function(e) {
					var value = this.value.replace(/\s+/g,"");
					if($(this).data("maxlength")&&value.length>$(this).data("maxlength")){
			        	this.value=value.substring(0,maxlength) ;
			        }
				});
			}
			if($this.data("style")){
				var dataStyle=$this.data("style");
				if(dataStyle=='english'||dataStyle=='long'||dataStyle=='double'||dataStyle=='currency'||dataStyle=='idcard'){
					$this.on("keyup",function(e) {
						this.value=this.value.replace(/[\u4e00-\u9fa5]/g,'');
					});
				}
				if($this.data("style")==="cardno"){
					$this.on("keyup",function(e) {
						this.value = this.value.replace(/(\d{4})(?=\d)/g,"$1"+" "); 
					});
				}else if($this.data("style")==="idcard"){
					$this.on("keyup",function(e) {
						this.value = this.value.replace(/(^\d{6}|\d{8})(?=\d)/g,"$1"+" ");
					});
				}else if($this.data("style")==="phone"){
					$this.on("keyup",function(e) {
						this.value = this.value.replace(/(^\d{3}|\d{4})(?=\d)/g,"$1"+" ");
					});
				}
			}
			
			if($this.data("format")){
				
			}
			
			if($this.data("transform")){
				if($this.data("transform")==="uppercase"){
					$this.css("text-transform","uppercase");
					$this.on("keyup",function(e) {
						this.value=this.value.toUpperCase();
					});
				}else if($this.data("transform")==="lowercase"){
					$this.css("text-transform","lowercase");
					$this.on("keyup",function(e) {
						this.value=this.value.toLowerCase()();
					});
				}
			}
		});
	};
	
	initPage=function() {  
		var winheigth=$(window).height();
		var margin=0;
		if($("#contant").data("margin")){
			margin=$("#contant").data("margin");
		}
		$("#contant").height(winheigth-50-margin);
    };  
})(jQuery);


//令牌
$().ready(function() {
	var winheigth=$(window).height();
	initPage();
	$(window).resize(function() {
		initPage();
	});
	
	//initInput();
	
	var $menuDialog;
	$(".menu a").click(function() {
		if($(".menu .items")){
			if (!$menuDialog) {
				$menuDialog = $('<div class="menuDialog"><\/div>').appendTo("body");
				var $menuUl=$('<ul><\/ul>').appendTo($menuDialog);
				$(".menu .items li").each(function (){  
		            var txt = $(this).text();  
		            var hr = $(this).data("href");  
		            $('<li><a href="'+hr+'">'+txt+'</a></li>').appendTo($menuUl);
		         }); 
    		}
		}
		$menuDialog.show();
		setTimeout(function() {
			$menuDialog.hide();
		}, 3000);
    });  
	
	$("form").submit(function() {
		var $this = $(this);
		if ($this.attr("method") != null && $this.attr("method").toLowerCase() == "post" && $this.find("input[name='token']").size() == 0) {
			var token = getCookie("token");
			if (token != null) {
				$this.append('<input type="hidden" name="token" value="' + token + '" \/>');
			}
		}
	});
	
	jQuery(".formContent select").each(function(index){
		$(this).selectBox();
	});
	
	$("input[type='number']").bind("paste", function() {           
        var s = window.clipboardData.getData('text');  
        if (!/\D/.test(s));  
        value = s.replace(/^0*/, '');  
        return false;  
    });  
    var format = function(value, scale){  
        return Math.round(value * Math.pow(10, scale)) / Math.pow(10, scale);  
    };         
    Array.indexOf = function(array, value) {  
        for (var i = 0; i < array.length; i++) {  
            if (value == array[i]) {  
                return i;  
            }  
        }  
        return -1;  
    };  

});
